package com.witframework.web.mvc;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.witframework.WitException;
import com.witframework.util.BeanUtils;
import com.witframework.util.StringTools;

/**
 * 
 * @author wuxinyang
 * May 12, 2009 2:33:26 PM
 *
 */
public final class WitActionHelper {
	private static Log log = LogFactory.getLog(WitActionHelper.class);
	public static void setEncoding(WebContext webContext){
		try {
			webContext.getHttpRequest().setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
			throw new WitException(localUnsupportedEncodingException);
		}
		webContext.getHttpResponse().setContentType("text/xml; charset=UTF-8");
		webContext.getHttpResponse().setHeader("Cache-Control", "no-store, max-age=0, no-cache");
		webContext.getHttpResponse().addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
		webContext.getHttpResponse().setHeader("Pragma", "no-cache");
	}
	public static String invoke(Object controller,String command, WebContext webContext) throws WitException {
		if(StringUtils.isEmpty(command)){
			if(controller instanceof Controller)
				return ((Controller)controller).executor(webContext);
			else
				command="executor" ;
		}
		try {
			Method commandMethod=BeanUtils.getMethod(controller,command,WebContext.class);
			if(commandMethod==null){
				log.info("not found method in controller("+controller.getClass().getName()+"):"+command+",will invoke method:default"+StringTools.upperCaseFirstAlpha(command));
				commandMethod=controller.getClass().getMethod("default"+StringTools.upperCaseFirstAlpha(command),WebContext.class);
			}
			log.debug("invoke controller:"+commandMethod);
			return (String)commandMethod.invoke(controller, webContext);
		}catch (NoSuchMethodException e) {
			throw new WitException("not found method in controller("+controller.getClass().getName()+"):"+command);
		}catch (InvocationTargetException e) {
			throw new WitException(e.getTargetException());
		}catch (IllegalArgumentException e) {			
			throw new WitException(e);
		}catch (IllegalAccessException e) {			
			throw new WitException(e);
		}
	}
}
